﻿using Microsoft.AspNetCore.Mvc;
using LPP.Service.OrderServices;
using LPP.API.Models;

using LPP.Service.payment;
using LPP.Service.Payment;

namespace LPP.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AlipayController : ControllerBase
{
    private readonly IPaymentService _paymentService;
    private readonly IOrderService _orderService;
    private readonly ILogger<AlipayController> _logger;

    public AlipayController(
        IPaymentService paymentService,
        IOrderService orderService,
        ILogger<AlipayController> logger)
    {
        _paymentService = paymentService;
        _orderService = orderService;
        _logger = logger;
    }

    [HttpPost("create")]
    [ProducesResponseType(typeof(PaymentResponse), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> CreatePayment([FromBody] CreatePaymentRequest request)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new ErrorResponse("无效的请求参数"));
            }

            var order = await _orderService.GetOrderByIdAsync(request.OrderId);
            if (order == null)
            {
                return NotFound(new ErrorResponse("订单不存在"));
            }

            if (order.Status != OrderStatus.Pending)
            {
                return BadRequest(new ErrorResponse($"订单状态不正确: {order.Status}"));
            }

            var payInfo = await _paymentService.CreatePaymentAsync(order);

            return Ok(new PaymentResponse
            {
                Success = true,
                OrderInfo = payInfo,
                OrderId = order.OrderID,
                Amount = order.Amount
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建支付宝订单失败: {@Request}", request);
            return StatusCode(500, new ErrorResponse("创建支付失败"));
        }
    }

    [HttpPost("notify")]
    public async Task<IActionResult> Notify()
    {
        try
        {
            var parameters = Request.Form.ToDictionary(k => k.Key, v => v.Value.ToString());
            _logger.LogInformation("收到支付宝通知: {@Parameters}", parameters);

            if (!_paymentService.VerifyNotify(parameters))
            {
                _logger.LogWarning("支付宝通知签名验证失败");
                return BadRequest("fail");
            }

            var result = await _paymentService.HandlePaymentNotifyAsync(parameters);
            return Content(result ? "success" : "fail");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理支付宝通知失败");
            return Content("fail");
        }
    }

    [HttpPost("verify")]
    [ProducesResponseType(typeof(VerifyResponse), StatusCodes.Status200OK)]
    public async Task<IActionResult> VerifyPayment([FromBody] VerifyPaymentRequest request)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new ErrorResponse("无效的请求参数"));
            }

            var order = await _orderService.GetOrderByIdAsync(request.OrderId);
            if (order == null)
            {
                return NotFound(new ErrorResponse("订单不存在"));
            }

            var verifyResult = await _paymentService.VerifyPaymentAsync(
                request.OrderId,
                request.TradeNo
            );

            return Ok(new VerifyResponse
            {
                Success = true,
                Paid = order.Status == OrderStatus.Completed || verifyResult,
                Status = order.Status.ToString(),
                PaidTime = order.PaidAt,
                TransactionId = order.TransactionId
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证支付状态失败: {@Request}", request);
            return StatusCode(500, new ErrorResponse("验证支付失败"));
        }
    }
}